/*
 * DILARANG MENGHAPUS ATAU MENGEDIT COPYRIGHT INI.
 * 
 * Copyright 2008 echo.khannedy@gmail.com. 
 * All rights reserved.
 * 
 * Semua isi dalam file ini adalah hak milik dari echo.khannedy@gmail.com
 * Anda tak diperkenankan untuk menggunakan file atau mengubah file
 * ini kecuali anda tidak menghapus atau merubah lisence ini.
 * 
 * File ini dibuat menggunakan :
 * IDE        : NetBeans
 * NoteBook   : Acer Aspire 5920G
 * OS         : Windows Vista
 * Java       : Java 1.6
 * 
 */
package usu.perpustakaan.buku.widget.admin;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import usu.perpustakaan.buku.data.MySQLAdmin;
import usu.perpustakaan.buku.util.StringUtil;
import usu.widget.ButtonGlass;
import usu.widget.Panel;
import usu.widget.util.WidgetUtilities;

/**
 *
 * @author  usu
 */
public class ManageMySQL extends Panel implements DocumentListener {

    private static final long serialVersionUID = -1;
    private ObjectInputStream stream;
    private MySQLAdmin admin;
    private String host;
    private String port;
    private String database;
    private Connection connection;

    /** Creates new form BeanForm */
    public ManageMySQL() {
        initComponents();
        textDatabase.getDocument().addDocumentListener(this);
        textHost.getDocument().addDocumentListener(this);
        textPort.getDocument().addDocumentListener(this);
    }

    /**
     * refresh
     */
    public void refresh() {
        try {
            stream = new ObjectInputStream(new FileInputStream("setting\\admin.ebl"));
            admin = (MySQLAdmin) stream.readObject();
        } catch (IOException ex) {
            WidgetUtilities.showErrorMessage(this, ex.getMessage());
            System.exit(1);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ManageMySQL.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException ex) {
                    Logger.getLogger(ManageMySQL.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            Properties prop = new Properties();
            try {
                prop.loadFromXML(new FileInputStream("setting\\database.xml"));
            } catch (IOException ex) {
                WidgetUtilities.showErrorMessage(this, ex.getMessage());
                System.exit(1);
            }
            host = prop.getProperty("host");
            port = prop.getProperty("port");
            database = prop.getProperty("database");
            textHost.setText(host);
            textPort.setText(port);
            textDatabase.setText(database);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usu.perpustakaan.buku.widget.template.ViewPortGlass view = new usu.perpustakaan.buku.widget.template.ViewPortGlass();
        areaExecutor = new javax.swing.JTextArea();
        usu.perpustakaan.buku.widget.template.PanelTranparan panelTranparan1 = new usu.perpustakaan.buku.widget.template.PanelTranparan();
        javax.swing.JLabel jLabel1 = new javax.swing.JLabel();
        javax.swing.JLabel jLabel2 = new javax.swing.JLabel();
        javax.swing.JLabel jLabel3 = new javax.swing.JLabel();
        textHost = new usu.perpustakaan.buku.widget.template.TextBoxGlass();
        textPort = new usu.perpustakaan.buku.widget.template.TextBoxGlass();
        textDatabase = new usu.perpustakaan.buku.widget.template.TextBoxGlass();
        buttonTestConnection = new usu.widget.ButtonGlass();
        usu.widget.ButtonGlass buttonReset = new usu.widget.ButtonGlass();
        buttonSave = new usu.widget.ButtonGlass();

        view.setView(areaExecutor);

        areaExecutor.setColumns(20);
        areaExecutor.setFont(new java.awt.Font("Tahoma", 1, 11));
        areaExecutor.setForeground(new java.awt.Color(255, 255, 255));
        areaExecutor.setRows(5);
        areaExecutor.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
        areaExecutor.setOpaque(false);

        setOpaque(false);
        setOpaqueGradient(false);
        setOpaqueImage(false);

        panelTranparan1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 3));
        panelTranparan1.setRound(false);

        jLabel1.setDisplayedMnemonic('H');
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Host");

        jLabel2.setDisplayedMnemonic('P');
        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Port");

        jLabel3.setDisplayedMnemonic('D');
        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Database");

        textHost.setForeground(new java.awt.Color(255, 255, 255));
        textHost.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        textHost.setToolTipText("Masukkan host");
        textHost.setFocusAccelerator('H');
        textHost.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        textHost.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textHostActionPerformed(evt);
            }
        });

        textPort.setForeground(new java.awt.Color(255, 255, 255));
        textPort.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        textPort.setToolTipText("Masukkan port");
        textPort.setFocusAccelerator('P');
        textPort.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        textPort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textPortActionPerformed(evt);
            }
        });

        textDatabase.setForeground(new java.awt.Color(255, 255, 255));
        textDatabase.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        textDatabase.setToolTipText("Masukkan nama database");
        textDatabase.setFocusAccelerator('D');
        textDatabase.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        textDatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textDatabaseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelTranparan1Layout = new javax.swing.GroupLayout(panelTranparan1);
        panelTranparan1.setLayout(panelTranparan1Layout);
        panelTranparan1Layout.setHorizontalGroup(
            panelTranparan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTranparan1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelTranparan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelTranparan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textPort, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
                    .addComponent(textHost, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
                    .addComponent(textDatabase, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE))
                .addContainerGap())
        );
        panelTranparan1Layout.setVerticalGroup(
            panelTranparan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTranparan1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelTranparan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelTranparan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelTranparan1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        buttonTestConnection.setMnemonic('T');
        buttonTestConnection.setText("Tes Koneksi");
        buttonTestConnection.setToolTipText("Klik untuk mentest koneksi");
        buttonTestConnection.setRoundRect(true);
        buttonTestConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonTestConnectionActionPerformed(evt);
            }
        });

        buttonReset.setMnemonic('R');
        buttonReset.setText("Reset");
        buttonReset.setToolTipText("Klik untuk mengubah ke pengaturan awal");
        buttonReset.setRoundRect(true);
        buttonReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonResetActionPerformed(evt);
            }
        });

        buttonSave.setMnemonic('S');
        buttonSave.setText("Simpan");
        buttonSave.setToolTipText("Klik untuk menyimpan perubahan");
        buttonSave.setEnabled(false);
        buttonSave.setRoundRect(true);
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelTranparan1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(buttonTestConnection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonReset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelTranparan1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonReset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonTestConnection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(257, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
    try {
        Properties prop = new Properties();
        prop.put("host", textHost.getText());
        prop.put("port", textPort.getText());
        prop.put("database", textDatabase.getText());
        prop.storeToXML(new FileOutputStream("setting\\database.xml"), "e'BookLibrary Database Setting");//GEN-LAST:event_buttonSaveActionPerformed
        } catch (IOException ex) {
            Logger.getLogger(ManageMySQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

private void buttonTestConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTestConnectionActionPerformed
    if (stream == null) {
        refresh();
    }
    database = textDatabase.getText();
    host = textHost.getText();
    port = textPort.getText();
    try {
        connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database,
                StringUtil.getStringFromArrayChar(admin.getUsername("NESIAOKTIANA")),
                StringUtil.getStringFromArrayChar(admin.getPassword("NESIAOKTIANA")));
        buttonSave.setEnabled(true);
        JOptionPane.showMessageDialog(this, "Connection Success, Click Save Button to Save It");
    } catch (SQLException ex) {
        buttonSave.setEnabled(false);
        connection = null;
        WidgetUtilities.showErrorMessage(this, ex.getMessage());
    }
}//GEN-LAST:event_buttonTestConnectionActionPerformed

private void buttonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonResetActionPerformed
    Properties prop = new Properties();
    try {
        prop.loadFromXML(new FileInputStream("setting\\database.xml"));
    } catch (IOException ex) {
        WidgetUtilities.showErrorMessage(this, ex.getMessage());
        System.exit(1);
    }
    host = prop.getProperty("host");
    port = prop.getProperty("port");
    database = prop.getProperty("database");
    textHost.setText(host);
    textPort.setText(port);
    textDatabase.setText(database);
}//GEN-LAST:event_buttonResetActionPerformed

private void textHostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textHostActionPerformed
    textHost.transferFocus();
}//GEN-LAST:event_textHostActionPerformed

private void textPortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textPortActionPerformed
    textPort.transferFocus();
}//GEN-LAST:event_textPortActionPerformed

private void textDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textDatabaseActionPerformed
    buttonTestConnection.requestFocusInWindow();
}//GEN-LAST:event_textDatabaseActionPerformed

    /**
     * 
     * @return
     */
    public ButtonGlass getButtonTestConnection() {
        return buttonTestConnection;
    }

    /**
     * 
     * @return
     * @throws java.lang.NullPointerException 
     */
    public Connection getConnection() throws NullPointerException {
        if (connection == null) {
            throw new NullPointerException();
        }
        return connection;
    }

    /**
     * 
     * @return
     */
    public JTextArea getAreaExecutor() {
        return areaExecutor;
    }

    /**
     * 
     * @param areaExecutor
     */
    public void setAreaExecutor(JTextArea areaExecutor) {
        this.areaExecutor = areaExecutor;
    }

    /**
     * 
     * @return
     */
    public ButtonGlass getButtonSave() {
        return buttonSave;
    }

    /**
     * 
     * @return
     */
    public String[] getExecutionString() {
        ArrayList<String> array = new ArrayList<String>();
        String total = areaExecutor.getText();

        StringTokenizer token = new StringTokenizer(total, ";");
        while (token.hasMoreElements()) {
            array.add(token.nextToken());
        }

        return array.toArray(new String[array.size()]);
    }

    /**
     * 
     * @param buttonSave
     */
    public void setButtonSave(ButtonGlass buttonSave) {
        this.buttonSave = buttonSave;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    javax.swing.JTextArea areaExecutor;
    usu.widget.ButtonGlass buttonSave;
    usu.widget.ButtonGlass buttonTestConnection;
    usu.perpustakaan.buku.widget.template.TextBoxGlass textDatabase;
    usu.perpustakaan.buku.widget.template.TextBoxGlass textHost;
    usu.perpustakaan.buku.widget.template.TextBoxGlass textPort;
    // End of variables declaration//GEN-END:variables

    @Override
    public void insertUpdate(DocumentEvent e) {
        buttonSave.setEnabled(false);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        buttonSave.setEnabled(false);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        buttonSave.setEnabled(false);
    }
}
